import serial
import threading
import selectors
import sys


def read_and_write(port: serial.Serial):
    sel = selectors.DefaultSelector()
    sel.register(port, selectors.EVENT_READ, 'serial')
    sel.register(sys.stdin, selectors.EVENT_READ, 'stdin')
    while True:
        events = sel.select()
        for key, _ in events:
            if key.data == 'serial':
                print(port.readline().decode('utf8').rstrip('\n'))
            elif key.data == 'stdin':
                port.write(sys.stdin.readline().encode('utf8'))


if __name__ == '__main__':
    port = serial.Serial(sys.argv[1], 115200)
    read_and_write(port)